package site.wenneng.dev.service;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

public class BaseService {

    @Autowired
    private FreeMarkerConfigurer configurer;
    @Autowired
    private OkHttpClient httpClient;


    public String processRequest(String ftl, Object dataModel) {
        Configuration configuration = configurer.getConfiguration();
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        try {
            Template template = configuration.getTemplate(ftl);
            template.process(dataModel, new OutputStreamWriter(out));
            return out.toString();
        } catch (IOException | TemplateException e) {
            throw new RuntimeException(e);
        }
    }

    public String invoke(Request request) {
        try (Response res = httpClient.newCall(request).execute()) {
            ResponseBody body = res.body();
            if (body != null) {
                return body.string();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return "";
    }

    protected ObjectMapper getObjectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE);
        return objectMapper;
    }
}
